/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elsimulatorjava;

import elsimulatorjava.Elevator.ElevatorDirection;
import java.awt.FileDialog;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Date;
import java.util.Set;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFileChooser;

/**
 *
 * @author corey
 */
//public class Building implements Runnable{
public class Building {
    private Floor[] floors; //Holds a counter of the people on the floor
    private Elevator[] elevators;
    
    private short highestFloor;
    private short lowestFloor;
    
    private byte peopleProb;
    
    private Date timer = new Date();
   

    Random rand = new Random();

    public Building(Elevator[] elevatorArr, Floor[] floorArr, byte pplProb){
        this.highestFloor = (short)(floorArr.length-1);
        this.lowestFloor = 0;
        this.elevators = elevatorArr;
        this.floors = floorArr;
        this.peopleProb = pplProb;
    }


    public void run() {
        if ((new Date().getTime()-timer.getTime()) > 100){
            if ((rand.nextInt(100)) > (100-peopleProb)){
                this.createRandomPerson();
                timer = new Date();
            }
        }
//        System.out.println("Entering cycle");
        for (Elevator elevator : elevators) {
//        System.out.println("Elevator " + elevator.getElevatorIdx() + " goes in direction " + elevator.getDirection() + " doorSize " + elevator.getDoor() + " state: "  + elevator.getState());
        switch (elevator.getState()) {
            case MOVING:
                elevator.changePosition();
                if (elevator.getProperPosition() -elevator.getPosition() == 0 ) {
                    doorOpeningCheck(elevator);
                }
                if (elevator.getLastFloor() == elevator.getPosition() 
                        && elevator.getState() != Elevator.ElevatorState.DOOR_OPENING) {
                    elevator.setState(Elevator.ElevatorState.IDLE);
                    elevator.setDirection(ElevatorDirection.NONE);
                }
//                System.out.println("Elevator Moving");
//                System.out.println(elevator.getPosition());
                break;

            case DOOR_OPENING:
                elevator.changeDoorSize((byte)1);
                if (elevator.getDirection() == Elevator.ElevatorDirection.UP){
                        floors[elevator.getPosition()].setUpLock(true);
                    } else if (elevator.getDirection() == Elevator.ElevatorDirection.DOWN) {
                        floors[elevator.getPosition()].setDownLock(true);
                    }
//                System.out.println("Door Opening");
                break;

            case DOOR_OPEN:
                this.movePeople(elevator, floors[elevator.getPosition()]);
                if (floors[elevator.getPosition()].getPeopleWaiting().size() > 0 && elevator.getPosition() == 0) 
                {
                    elevator.setDirection(Elevator.ElevatorDirection.UP);
                    this.movePeople(elevator, floors[elevator.getPosition()]);
                }
                else if (floors[elevator.getPosition()].getPeopleWaiting().size() > 0 && elevator.getPosition() == elevator.getMaxFloor())
                {
                    elevator.setDirection(Elevator.ElevatorDirection.DOWN);
                    this.movePeople(elevator, floors[elevator.getPosition()]);
                }
                else if (floors[elevator.getPosition()].getPeopleWaiting().size() > 0 && elevator.getDirection() == Elevator.ElevatorDirection.DOWN && elevator.getPeople().isEmpty())
                {
                    floors[elevator.getPosition()].setDownLock(false);
                    floors[elevator.getPosition()].setDownButtonOn(false);
                    elevator.setDirection(Elevator.ElevatorDirection.UP);
                    this.movePeople(elevator, floors[elevator.getPosition()]);
                }
                else if (floors[elevator.getPosition()].getPeopleWaiting().size() > 0 && elevator.getDirection() == Elevator.ElevatorDirection.UP && elevator.getPeople().isEmpty())
                {
                    floors[elevator.getPosition()].setUpLock(false);
                    floors[elevator.getPosition()].setUpButtonOn(false);
                    elevator.setDirection(Elevator.ElevatorDirection.DOWN);
                    this.movePeople(elevator, floors[elevator.getPosition()]);
                }
                break;
                
//            case DOOR_OPEN:
//                this.movePeople(elevator, floors[elevator.getPosition()]);
////                System.out.println("Door Open");
//                break;

            case DOOR_CLOSING:
                if (elevator.isNotFull()){
                    doorOpeningCheck(elevator);
                }
                if (elevator.getState() == Elevator.ElevatorState.DOOR_CLOSING){
                    elevator.changeDoorSize((byte)-1);
                }
                
                if (elevator.isDoorClosed()){
                    if (elevator.getDirection() == Elevator.ElevatorDirection.UP){
                        floors[elevator.getPosition()].setUpLock(false);
                        floors[elevator.getPosition()].setUpButtonOn(false);
                    } else if (elevator.getDirection() == Elevator.ElevatorDirection.DOWN) {
                        floors[elevator.getPosition()].setDownLock(false);
                        floors[elevator.getPosition()].setDownButtonOn(false);
                    } else if (elevator.getState() == Elevator.ElevatorState.IDLE || elevator.getDirection() == Elevator.ElevatorDirection.NONE){
                        floors[elevator.getPosition()].setDownLock(false);
                        floors[elevator.getPosition()].setDownButtonOn(false);
                        floors[elevator.getPosition()].setUpLock(false);
                        floors[elevator.getPosition()].setUpButtonOn(false);
                    }
                }
                
                
                /*if (elevator.getState() == Elevator.ElevatorState.MOVING && !elevator.noPeopleInside()) {
                    setLastFloorToGoTo(elevator.getElevatorID(), elevator.getLastFloorToGoTo());
                }*/
               /* if (elevator.noPeopleInside() && ){
                    elevator.setState(Elevator.ElevatorState.IDLE);
                }*/
//                System.out.println("Door Closing");

                break;

            case IDLE:
//                System.out.println("Elevator idle " + elevator.getDirection());
                elevator.setDirection(ElevatorDirection.NONE);
                if (elevator.getPosition() < (highestFloor-lowestFloor)/2) {
                    if (floors[elevator.getPosition()].isUpButtonOn()) {
                        elevator.setState(Elevator.ElevatorState.DOOR_OPENING);
                        elevator.setDirection(Elevator.ElevatorDirection.UP);
                        break;
                    }
                    getLockAboveElevator(floors, elevator, Elevator.ElevatorDirection.UP);
                    if (elevator.getLastFloor() == elevator.getPosition()) {
                        getLockAboveElevator(floors, elevator, Elevator.ElevatorDirection.DOWN);
                    }
                    if (elevator.getLastFloor() != elevator.getPosition()) {
                        break;
                    }
                    if (floors[elevator.getPosition()].isDownButtonOn() && !floors[elevator.getPosition()].isDownLockOn()) {
                        elevator.setState(Elevator.ElevatorState.DOOR_OPENING);
                        elevator.setDirection(Elevator.ElevatorDirection.DOWN);
                        break;
                    }
                    getLockBelowElevator(floors, elevator, Elevator.ElevatorDirection.DOWN);
                    if (elevator.getLastFloor() == elevator.getPosition()) {
                        getLockBelowElevator(floors, elevator, Elevator.ElevatorDirection.UP);
                        break;
                    }

                }
                else {
                    if (floors[elevator.getPosition()].isDownButtonOn()) {
                        elevator.setState(Elevator.ElevatorState.DOOR_OPENING);
                        elevator.setDirection(ElevatorDirection.DOWN);
                        break;
                    }
                    getLockBelowElevator(floors, elevator, ElevatorDirection.DOWN);
                    if (elevator.getLastFloor() == elevator.getPosition()) {
                        getLockBelowElevator(floors, elevator, ElevatorDirection.UP);
                    }
                    if (elevator.getLastFloor() != elevator.getPosition()) {
                        break;
                    }
                    if (floors[elevator.getPosition()].isUpButtonOn() && !floors[elevator.getPosition()].isUpLockOn()) {
                        elevator.setDirection(ElevatorDirection.UP);
                        elevator.setState(Elevator.ElevatorState.DOOR_OPENING);
                        break;
                    }
                    getLockAboveElevator(floors, elevator, ElevatorDirection.UP);
                    if (elevator.getPosition() == elevator.getLastFloor()) {
                        getLockAboveElevator(floors, elevator, ElevatorDirection.DOWN);
                        break;
                    }
                }
            }
        }

        for (Floor floor : floors){
            List<Person> people = floor.getPeople();
            for (int i = 0; i < people.size(); i++) {
                if (people.get(i).isFinished()) {
                    if (people.get(i).timeSinceFinish() > 5000) {
                        people.remove(i);
                    }
                }
            }
//            System.out.print(floor.getPeople().size()+ " ");
        }
//        System.out.println("\n");
    }

        

    protected void createRandomPerson()
    {
        if (rand.nextInt(10) >= 8)
        {
            short position = (short) (java.lang.Math.abs(rand.nextInt()%(this.highestFloor))+this.lowestFloor);
            short floorDst;
            do {
                floorDst = (short) (java.lang.Math.abs(rand.nextInt()%(this.highestFloor))+this.lowestFloor);
            } while (floorDst == position);

            floors[position].addPerson(new Person(floorDst));
        }
    }

    private void doorOpeningCheck(Elevator e){
        if (!e.isNotFull()) {
            for (Person person : e.getPeople()){
                if (person.getFloorDest() == e.getPosition()){
                    e.setState(Elevator.ElevatorState.DOOR_OPENING);
                    return;
                }
            }
        } else if (e.getDirection() == Elevator.ElevatorDirection.UP && floors[e.getPosition()].isUpButtonOn() && !floors[e.getPosition()].isUpLockOn()){
            floors[e.getPosition()].setUpLock(true);
            //e.setLastFloor(e.getPosition());
            e.setState(Elevator.ElevatorState.DOOR_OPENING);
        } else if (e.getDirection() == Elevator.ElevatorDirection.DOWN && floors[e.getPosition()].isDownButtonOn() && !floors[e.getPosition()].isDownLockOn()){
            floors[e.getPosition()].setDownLock(true);
            //e.setLastFloor(e.getPosition());
            e.setState(Elevator.ElevatorState.DOOR_OPENING);
        }
        for (Person person : floors[e.getPosition()].getPeople()){
            if (person.getFloorDest() > e.getPosition()){
                floors[e.getPosition()].setUpButtonOn(true);
                if (e.getDirection() == Elevator.ElevatorDirection.UP){
                    e.setState(Elevator.ElevatorState.DOOR_OPENING);
                }
            } else if (person.getFloorDest() < e.getPosition()){
                floors[e.getPosition()].setDownButtonOn(true);
                if (e.getDirection() == Elevator.ElevatorDirection.DOWN){
                    e.setState(Elevator.ElevatorState.DOOR_OPENING);
                }
            }
        }
    }

    private void movePeople(Elevator elevator, Floor floor) {
       
        
        // Get all the people that wants to leave elevator
        ArrayList<Person> removeFromList = new ArrayList<Person>();
        for (Person person : elevator.getPeople()) {
            if (person.getFloorDest() == elevator.getPosition()) {
                removeFromList.add(person);
            }
        }
        
        // Remove the people that wants to leave elevator
        for (Person person : removeFromList) {
            elevator.getPeople().remove(person);
        }
        
        // Add the people that wants to leave elevator to floor and set finished
        for (Person person : removeFromList) {
            person.setFinished();
            floor.getPeople().add(person);
        }
        
        // Clear the list so it can be reused
        removeFromList.clear();
        
        
        if (elevator.getDirection() == Elevator.ElevatorDirection.UP) {
            // Get all people that wants to go with the elevator
            for (Person person : floor.getPeople()) {
                if (person.getFloorDest() > elevator.getPosition()) {
                    removeFromList.add(person);
                }
            }
        
            // Removes people from floor that are on the remove from list
            for (Person person : removeFromList) {
                floor.removePerson(person);
            }
        
            // Adds a person to the elevator as long as it has space
            for (Person person : removeFromList) {
                if (elevator.getMaxNumberOfPeople()> elevator.getPeopleCount()) {
                    elevator.addPerson(person);
                }
            }
            
            // Removes the people from the remove from list that are in the elevator
            for(Person person : elevator.getPeople()) {
                removeFromList.remove(person);
            }
            
            // Adds the remainder of remove from list to the floor 
            for (Person person : removeFromList) {
                floor.addPerson(person);
            }
            removeFromList.clear();
        }
        else if (elevator.getDirection() == Elevator.ElevatorDirection.DOWN) {
            // Get all people that wants to go with the elevator
            for (Person person : floor.getPeople()) {
                if (person.getFloorDest() < elevator.getPosition()) {
                    removeFromList.add(person);
                }
            }
        
            // Removes people from floor that are on the remove from list
            for (Person person : removeFromList) {
                floor.removePerson(person);
            }
        
            // Adds a person to the elevator as long as it has space
            for (Person person : removeFromList) {
                if (elevator.getMaxNumberOfPeople()> elevator.getPeopleCount()) {
                    elevator.addPerson(person);
                }
            }
            
            // Removes the people from the remove from list that are in the elevator
            for(Person person : elevator.getPeople()) {
                removeFromList.remove(person);
            }
            
            // Adds the remainder of remove from list to the floor 
            for (Person person : removeFromList) {
                floor.addPerson(person);
            }
            removeFromList.clear();
        }
        
//        for (int i = 0; i < elevator.getPeople().size(); i++){
//           if (elevator.getPeople().get(i).getFloorDest() ==  elevator.getPosition()){
//               Person tempPerson = elevator.getPeople().get(i);
//               floors[elevator.getPosition()].addPerson(tempPerson);
//               elevator.removePerson(tempPerson);
//               tempPerson.setFinished();
//           }
//        }
//
//        
//        
//        
//        ArrayList<Person> people = floors[elevator.getPosition()].getPeopleWaiting();
//
//        if (elevator.getDirection() == Elevator.ElevatorDirection.UP){
//           for (int i = 0; i < people.size(); i++){
//               if (elevator.isNotFull()){
//                   if (people.get(i).getFloorDest() > elevator.getPosition()){
//                       elevator.addPerson(people.get(i));
//                       floors[elevator.getPosition()].removePerson(people.get(i));
//
//                   }
//               }
//           }
//        } else if (elevator.getDirection() == Elevator.ElevatorDirection.DOWN){
//           for (int i = 0; i < people.size(); i++){
//               if (elevator.isNotFull()){
//                   if (people.get(i).getFloorDest() < elevator.getPosition()){
//                       elevator.addPerson(people.get(i));
//                       floors[elevator.getPosition()].removePerson(people.get(i));
//                   }
//               }
//           }
//        }
        
        elevator.setState(Elevator.ElevatorState.DOOR_CLOSING);

    }

    private static Person getPersonFromFloor(Floor floor, byte direction) {
        List<Person> peopleWaiting = floor.getPeople();
        for(Person person : peopleWaiting) {
            if (personWantsToGoSameWayAsElevator(person, floor.getIndex(), direction)) {
                return person;
            }
        }
        return null;
    }

    private static boolean personWantsToGoSameWayAsElevator(Person person, short floorNumber, byte direction) {
        if (person.getFloorDest()-floorNumber >= direction) {
            return true;
        }
        else if (person.getFloorDest()-floorNumber <= direction) {
            return true;
        }
        else return false;
    }

   /* private static void addPersonToRightQueue(Floor floor, int iD, Person personToQueue) {
        floor.getPersonsList().get(iD).add(personToQueue);
    }
*/
    private static boolean elevatorInUpperHalf(byte highestFloor, byte lowestFloor, Elevator elevator) {
        if ((byte) elevator.getPosition() >= (byte) ((highestFloor-lowestFloor)/2)){
            return true;
        }
        else return false;
    }


    int getNumberOfFloors() {
        return this.floors.length;
    }
    
    void setFloors(Floor[] f) {
        this.floors = f;
    }
    
    Floor[] getFloors(){
        return this.floors;
    }
    
    void setElevators(Elevator[] e){
        this.elevators = e;
    }
    
    public Elevator[] getElevators(){
        return this.elevators;
    }

    public short getLowestFloor()
    {
        return lowestFloor;
    }

    public short getHighestFloor()
    {
        return highestFloor;
    }

    public Floor getFloor(int floorNumber) {
        return floors[floorNumber];
    }

  /*  void setLastFloorToGoTo(int iD, short lastFloorToGoTo) {
        lastFloorToGoToElevators[iD] = lastFloorToGoTo;
    }*/

   void save(Floor[] floors, Elevator[] elevators) throws Exception {
        Class.forName("org.sqlite.JDBC");
        JFileChooser chooser = new JFileChooser();
        chooser.showDialog(chooser, "Choose file motha***");
        File file = chooser.getSelectedFile();

        file.delete();
        
        Connection conn = DriverManager.getConnection("jdbc:sqlite:"+file.getAbsolutePath());
        
        Statement peopleDB = conn.createStatement();
        peopleDB.executeUpdate("drop table if exists People;");
        peopleDB.executeUpdate("create table People (ID, WhatPlace, IndexOfPosition, WantsToGoTo, isFinished, Timer);");
        PreparedStatement prepPeople = conn.prepareStatement("insert into People values (?, ?, ?, ?, ?, ?);");

        for(Floor floor : floors) {
            for (Person person : floor.getPeople()) {
                prepPeople.setInt(1, person.getIndex());
                prepPeople.setString(2, "Floor");
                prepPeople.setInt(3, floor.getIndex());
                prepPeople.setInt(4, person.getFloorDest());
                prepPeople.setBoolean(5, person.isFinished());
                prepPeople.setInt(6, person.timeSinceFinish());
                prepPeople.addBatch();
            }
        }
        for (Elevator elevator: elevators) {
            for (Person person : elevator.getPeople()) {
                prepPeople.setInt(1, person.getIndex());
                prepPeople.setString(2, "Elevator");
                prepPeople.setInt(3, elevator.getIndex());
                prepPeople.setInt(4, person.getFloorDest());
                prepPeople.setBoolean(5, person.isFinished());
                prepPeople.setInt(6, person.timeSinceFinish());
                prepPeople.addBatch();
            }
        }

        conn.setAutoCommit(false);
        prepPeople.executeBatch();
        prepPeople.clearBatch();
        conn.setAutoCommit(true);
        
        Statement elevatorDB = conn.createStatement();
        elevatorDB.executeUpdate("drop table if exists Elevator;");
        elevatorDB.executeUpdate("create table Elevator(Elevator_Index, "
                + "Floors_allowed, Elevator_state, Elevator_direction, "
                + "Last_floor_to_go_to, Door_opening, MaxFloor, MaxNumberOfPeople, CurrentPosDecimal, CurrentPosition);"); 
                
        PreparedStatement prepElevator = conn.prepareStatement("insert into Elevator values (?,?,?,?,?,?,?,?,?,?);");
        for (Elevator elevator : elevators) {
            prepElevator.setInt(1, elevator.getIndex());
            String allowedFloorsElevators = "";
            for (Boolean allowedFloor : elevator.getAllowedFloorList()) {
                allowedFloorsElevators += allowedFloor + " ";
            }

            prepElevator.setString(2, allowedFloorsElevators);
            prepElevator.setString(3, elevator.getState().toString());
            prepElevator.setString(4, elevator.getDirection().toString());
            prepElevator.setInt(5, elevator.getLastFloor());
            prepElevator.setInt(6, elevator.getDoorOpen());
            prepElevator.setInt(7, elevator.getMaxFloor());
            prepElevator.setByte(8, elevator.getMaxNumberOfPeople());
            prepElevator.setInt(9, elevator.getPosDecimal());
            prepElevator.setInt(10, elevator.getPosition());
            prepElevator.addBatch();
        }
        conn.setAutoCommit(false);
        prepElevator.executeBatch();
        prepElevator.clearBatch();
        conn.setAutoCommit(true);

        Statement floorDB = conn.createStatement();
        floorDB.executeUpdate("drop table if exists Floor");
        floorDB.executeUpdate("create table Floor(Floor_index, Floor_name,"
                + "UpLockOn, DownLockOn, UpButtonPushed, DownButtonPushed);");
        PreparedStatement prepFloor = conn.prepareStatement("insert into Floor values(?, ?, ?, ?, ?, ?);");

        for(Floor floor : floors) {
            prepFloor.setInt(1, floor.getIndex());
            prepFloor.setString(2, floor.getName());
            prepFloor.setBoolean(3, floor.isUpLockOn());
            prepFloor.setBoolean(4, floor.isDownLockOn());
            prepFloor.setBoolean(5, floor.isUpButtonOn());
            prepFloor.setBoolean(6, floor.isDownButtonOn());
            prepFloor.addBatch();
        }

        conn.setAutoCommit(false);
        prepFloor.executeBatch();
        prepFloor.clearBatch();
        conn.setAutoCommit(true);
        
        conn.close();
        
    }

       public void load() throws Exception {
            Class.forName("org.sqlite.JDBC");
            
            JFileChooser chooser = new JFileChooser();
            chooser.showDialog(chooser, "Choose file motha***");
            File file = chooser.getSelectedFile();
            //System.out.println(file.getAbsolutePath());
            Connection conn = DriverManager.getConnection("jdbc:sqlite:"+file.getAbsolutePath());
            Statement building = conn.createStatement();
            ResultSet accessData = building.executeQuery("select * from Floor");
            int k = 0;
            while (accessData.next()){
                k++;
            }
            accessData = building.executeQuery("select * from Floor");
            floors = new Floor[k];
            //System.out.println(accessData.getFetchSize());
            int i = 0;
            while (accessData.next()) {
                System.out.println(accessData.getString(2));
                floors[i] = new Floor(accessData.getString(2));
                floors[i].setUpLock(accessData.getBoolean(3));
                floors[i].setDownLock(accessData.getBoolean(4));
                floors[i].setUpButtonOn(accessData.getBoolean(5));
                floors[i].setDownButtonOn(accessData.getBoolean(6));
                i++;
            }
    
            accessData = building.executeQuery("select * from Elevator");
            k = 0;
            while (accessData.next()){
                k++;
            }
            accessData = building.executeQuery("select * from Elevator");
            i = 0;
            int j = 0;
            elevators = new Elevator[k];
            while (accessData.next()) {
                boolean[] floorListBoolean = new boolean[floors.length];
                String floorListString = accessData.getString(2);
                String[] floorListAllowedArray = floorListString.split(" "); 
                for (String allowed : floorListAllowedArray) {
                    floorListBoolean[i] = Boolean.parseBoolean(allowed);
                    i++;
                }

                elevators[j] = new Elevator((short)floors.length, (short)0, (short)0, accessData.getByte(8), floorListBoolean);
                elevators[j].setPosition((short)accessData.getInt(10));
                elevators[j].setPosDecimal(accessData.getInt(9));
                elevators[j].setDoorOpen(accessData.getInt(6));
                elevators[j].setState(Elevator.ElevatorState.valueOf(accessData.getString(3)));
                elevators[j].setDirection(Elevator.ElevatorDirection.valueOf(accessData.getString(4)));
                j++;
            }
    
            
    
            accessData = building.executeQuery("select * from People");
            
    
            while (accessData.next()) {
                Person person = new Person((short)accessData.getInt(4));
                person.setFromSavedFinished(accessData.getBoolean(5));
                if(person.isFinished()) {
                    person.setFinished();
                }
                if (accessData.getString(2) == "Elevator") {
                    elevators[accessData.getInt(3)].addPerson(person);
                }
                else {
                    floors[accessData.getInt(3)].addPerson(person);
                }
            }
    
            System.out.println("finish");
        }

    private ArrayList<Boolean> stringToBooleanList(String booleanValues){
        Scanner reader = new Scanner(booleanValues);
        ArrayList<Boolean> booleanList = null;
        String test;
        while (reader.hasNext()) {
            test = reader.next();
            if (test.equals("true")) {
                booleanList.add(true);
            }
            else {
                booleanList.add(false);
            }
        }
        return booleanList;
    }

    private Set<Integer> stringToIntegerList(String integerValues) {
        Scanner reader = new Scanner(integerValues);
        Set<Integer> integerList = null;
        while (reader.hasNext()) {
            integerList.add(reader.nextInt());
        }
        return integerList;
    }

    void createPerson(int i, int i0) {
        Person person = new Person((short)i0);
        this.addPersonToFloor(i, person);
    }

    private void addPersonToFloor(int i, Person person) {
        this.getFloors()[i].addPerson(person);
    }

    private void getLockAboveElevator(Floor[] floors, Elevator elevator, ElevatorDirection elevatorDirection) {
        if (elevatorDirection == ElevatorDirection.UP) {
            for (int i = elevator.getPosition() + 1; i < floors.length; i++) {
                if (floors[i].isUpButtonOn()) {
                    if (!floors[i].isUpLockOn()){
                        elevator.setDirection(ElevatorDirection.UP);
                        elevator.setState(Elevator.ElevatorState.MOVING);
                        elevator.setLastFloor((short) i);
                        floors[i].setUpLock(true);
                        return;
                    } else {
//                        System.out.println("dd");
                        return;
                    }
                }
            }
        } else if (elevatorDirection == ElevatorDirection.DOWN) {
            for (int i = floors.length-1; i > elevator.getPosition(); i--) {
                if (floors[i].isDownButtonOn()){
                    if (!floors[i].isDownLockOn()){
                        elevator.setDirection(ElevatorDirection.DOWN);
                        elevator.setState(Elevator.ElevatorState.MOVING);
                        //elevator.setDirectionAfterLock(ElevatorDirection.DOWN);
                        //elevator.setLock();
                        elevator.setLastFloor((short) i);
                        floors[i].setDownLock(true);
                        return;
                    } else {
//                        System.out.println("cc");
                        return;
                    }
                }
            }
        }
    }

    private void getLockBelowElevator(Floor[] floors, Elevator elevator, ElevatorDirection elevatorDirection) {
        if (elevatorDirection == ElevatorDirection.DOWN) {
            for (int i = elevator.getPosition()-1; i > lowestFloor; i--) {
                if (floors[i].isDownButtonOn()) {
                    if (!floors[i].isDownLockOn()){
                        elevator.setDirection(ElevatorDirection.DOWN);
                        elevator.setState(Elevator.ElevatorState.MOVING);
                        elevator.setLastFloor((short) i);
                        floors[i].setDownLock(true);
                        return;
                    } else {
//                        System.out.println("bb");
                        return;
                    }
                }
            }
        } else if (elevatorDirection == ElevatorDirection.UP){
            for (int i = lowestFloor; i < elevator.getPosition(); i++) {
                if (floors[i].isUpButtonOn()){
                    if (!floors[i].isUpLockOn()){
                        elevator.setDirection(ElevatorDirection.UP);
                        elevator.setState(Elevator.ElevatorState.MOVING);
                        //elevator.setLock();
                        //elevator.setDirectionAfterLock(ElevatorDirection.UP);
                        elevator.setLastFloor((short) i);
                        floors[i].setUpLock(true);
                        return;
                    } else {
//                        System.out.println("aa");
                        return;
                    }
                } 
            }
        }
    }
    
    protected short getElevatorCount(){
        return (short)elevators.length;
    }
    
    public double[] getElevatorPositions() {
        double[] elevatorPositions = new double[elevators.length];
        int i = 0;
        for (Elevator elevator : elevators) {
            elevatorPositions[i] = elevator.getProperPosition();
            i++;
        }
        return elevatorPositions;
    }

    public double[] getDoorOpenings() {
        double[] doorOpenings = new double[elevators.length];
        int i = 0;
        for (Elevator elevator : elevators) {
            doorOpenings[i]=elevator.getDoor();
            i++;
        }
        return doorOpenings;
        
    }
    
    void setPeopleProbability(byte p){
        this.peopleProb = p;
    }
}
